﻿using AutoMapper;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_Manage
{
    public class HomeBusiness : BaseBusiness<Base_User>, IHomeBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IMapper _mapper;
        readonly IConfiguration _config;
        public HomeBusiness(IDbAccessor db, IOperator @operator, IMapper mapper, IConfiguration @configuration)
            : base(db)
        {
            _operator = @operator;
            _mapper = mapper;
            _config = @configuration;
        }

        public async Task<string> SubmitLoginAsync(LoginInputDTO input)
        {
            input.password = input.password.ToMD5String();
            var theUser = await GetIQueryable().IgnoreQueryFilters()
                .Where(x => x.UserName == input.userName && x.Password == input.password)
                .FirstOrDefaultAsync();

            if (theUser.IsNullOrEmpty())
                throw new BusException("账号或密码不正确！");
            return theUser.Id;

            
        }

        public string GetTheToken(WeChatRequestModel model)
        {
            //获取请求来的 echostr 参数
            string echoStr = model.echostr;
            //通过验证，出于安全考虑。（也可以跳过）
            //if (CheckSignature(model))
            //{
            if (!string.IsNullOrEmpty(echoStr))
            {
                //将随机生成的 echostr 参数 原样输出
                return echoStr;
            }
            //}
            //else
            //{
            //    throw new BusException("Token验证失败，请重试！");
            //}

            return "";

        }

        public async Task ChangePwdAsync(ChangePwdInputDTO input)
        {
            var theUser = _operator.Property;
            if (theUser.Password != input.oldPwd?.ToMD5String())
                throw new BusException("原密码错误!");

            theUser.Password = input.newPwd.ToMD5String();
            await UpdateAsync(_mapper.Map<Base_User>(theUser));
        }
       
    }
}
